import * as vscode from 'vscode'
import { RecordService } from '../services/recordService'
import { CodeLensData } from '../types'
import { COMMANDS } from '../constants/commands'

export class CodeLensProvider implements vscode.CodeLensProvider {
  constructor(private recordService: RecordService) {}

  provideCodeLenses(document: vscode.TextDocument): vscode.CodeLens[] {
    const codeLenses: vscode.CodeLens[] = []
    const text = document.getText()
    const lines = text.split('\n')
    const records = this.recordService.getWorkspaceRecords()

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i]
      const match = line.match(/🔗 CodeMemo记录 #(\d+):/)

      if (match) {
        const recordId = parseInt(match[1])
        const record = records.find(r => r.id === recordId)

        if (record) {
          const range = new vscode.Range(i, 0, i, line.length)

          // 查看详情按钮
          const viewCommand: vscode.Command = {
            title: '👁️ 查看',
            command: COMMANDS.RECORD_DETAIL,
            arguments: [recordId]
          }

          // 编辑按钮
          const editCommand: vscode.Command = {
            title: '✏️ 编辑',
            command: COMMANDS.EDIT_RECORD,
            arguments: [recordId]
          }

          codeLenses.push(new vscode.CodeLens(range, viewCommand), new vscode.CodeLens(range, editCommand))
        }
      }
    }

    return codeLenses
  }
}
